package org.boot.thread.controller;

import org.boot.thread.service.ThreadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 线程相关Controller
 *
 * @author 李坤
 * @date 2022/8/19 9:14
 */
@RestController
@RequestMapping("/thread")
public class ThreadController {

    private final Logger logger = LoggerFactory.getLogger(ThreadController.class);

    @Resource
    private ThreadService threadService;

    @GetMapping("/thread/pool/{times}/{concurrency}")
    public boolean verityThreadPool(@PathVariable int times, @PathVariable int concurrency) throws InterruptedException {
        final List<Future<Boolean>> futureList = new ArrayList<>(times * concurrency);

        for (int t = 0; t < times; t++) {
            for (int c = 0; c < concurrency; c++) {
                futureList.add(threadService.verityThreadPool());
            }
            Thread.sleep(5000L);
        }
        logger.info("任务提交结束");
        return futureList.stream().anyMatch(future -> !get(future));
    }


    /*-------------------------------------------------private methods------------------------------------------------*/


    private <T> T get(Future<T> future) {
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException exception) {
            logger.error("获取异步线程执行结果失败");
            return null;
        }
    }

}
